import NProgress from "nprogress"; // 加载进度条
import "nprogress/nprogress.css"; // 进度条样式
NProgress.configure({
  showSpinner: false
}); // 配置
import store from '../store/index'
import { isLogin } from '../api/user'
import { Toast } from "vant";

const beforeEach = (to, from, next) => {

  // const list = ['index', 'task', 'center','message','user']    // 将需要切换效果的路由名称组成一个数组
  // const toName = to.name    // 即将进入的路由名字
  // const fromName = from.name    // 即将离开的路由名字
  const toIndex = to.meta.index    // 进入下标
  const fromIndex = from.meta.index   // 离开下标
  let direction = ''
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '热圈圈'
  }
  if (toIndex > -1 && fromIndex > -1) {   // 如果下标都存在
    if (toIndex < fromIndex) {          // 如果进入的下标小于离开的下标，那么是左滑
      direction = 'left'
    } else {
      direction = 'right'         // 如果进入的下标大于离开的下标，那么是右滑
    }
  }
  store.state.viewDirection = direction  //这里使用vuex进行赋值

  if (to.path == '/login' || to.path == '/register' || to.path == '/forget') {
    next()
  } else {
    if (localStorage.getItem('token')) {
      isLogin().then(res => {
        if (res.status == 400) {
          Toast(res.message);
          next({
            path: '/login'
          })
        }else{
          next()
        }
      })
    } else {
      next({
        path: '/login'
      })
    }
  }

  return next()
  NProgress.done();
}

export {
  beforeEach
}
